#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>

#define INPUT_COMMAND_SERVER_PORT (19081)

const char *CMD_REFRESH_STAT = "refresh_stat";
const char *CMD_REFRESH_NS_ROOT = "refresh_ns_root";

int create_message(char *dst, const char *cmd, const char *path)
{
    int n = 0;

    n += sprintf(&dst[n], "%s\n", cmd); 

    if (path != NULL && strlen(path) > 0) {
        n += sprintf(&dst[n], "path\t%s\n", path); 
    }

    n += sprintf(&dst[n], "done\n"); 

    return n;
}

int send_message(int udp_sock, const char *cmd, int len)
{
    struct sockaddr_in addr;

    /* intialize address structure */
    addr.sin_family = AF_INET;
    addr.sin_port = htons(INPUT_COMMAND_SERVER_PORT);
    inet_aton("127.0.0.1", &addr.sin_addr); 

    int n = sendto(udp_sock, cmd, len, 0, (struct sockaddr *)&addr, sizeof(addr));
    if (n < 0) {
        perror("UDP sendto error");
    } else if (n == 0) {
        printf("Sever has reset the UDP socket\n");
    } else {
        printf("UDP sendto() OK (len=%d):\n%s", n, cmd);
    }

    return n;
}

int main(int argc, char *argv[])
{
#define MAX_MESSGE_LEN (2048)
#define MAX_COMMAND_LEN (128)
#define MAX_PATH_LEN    (1024)

    char *msg;
    char *cmd;
    char *path;

    int udp_sock = -1;
    int i, n;

    udp_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (udp_sock < 0) {
        perror("UDP socket() Error");
        exit(-1);
    }

    msg = (char *)malloc(MAX_MESSGE_LEN+1);
    cmd = (char *)malloc(MAX_COMMAND_LEN+1);
    path = (char *)malloc(MAX_PATH_LEN+1);
 
    for (i = 1; i < argc; i++) {
        n = create_message(msg, "refreshs_stat", argv[1]); 
        send_message(udp_sock, msg, n);
    }

    while (1) {
        const char *arg = NULL;

        printf("\nType command (refresh_stat or refresh_ns_root): ");
        fgets(cmd, MAX_COMMAND_LEN, stdin);
        n = strlen(cmd);
        cmd[n-1] = '\0';

        if (strcmp(cmd, CMD_REFRESH_STAT) == 0) {
            printf("\nType path:");
            fgets(path, MAX_PATH_LEN, stdin);
            n = strlen(path);
            path[n-1] = '\0';

            arg = path;
        } else if (strcmp(cmd, CMD_REFRESH_NS_ROOT) != 0) {
            printf("ERROR: invalid command!\n");
            continue;
        }

        n = create_message(msg, cmd, arg); 
        send_message(udp_sock, msg, n);
    }

    return 0;
}

